<template>
  <div>
    <!-- 面包屑导航栏区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片内容区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- 搜索框 -->
        <el-col :span="7">
          <el-input placeholder="请输入内容" clearable @clear="clearInput" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList()"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户信息表格区域 -->
      <el-table :data="usersList" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <!-- switch显示状态修改 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->

        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditUser(scope.row.id)"
            ></el-button>

            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户对话框 -->
      <!-- 对话框头部 -->
      <el-dialog title="添加用户" :visible.sync="addUserVisible" width="30%" @closed="adduserClosed">
        <!-- 对话框主体 -->
        <el-form :model="adduserForm" :rules="adduserrules" ref="adduserForm" label-width="20%">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="adduserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="adduserForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="adduserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="adduserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 对话框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserCheck">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 修改用户信息的对话框 -->
    <!-- 对话框头部 -->
    <el-dialog title="修改用户信息" :visible.sync="editUserVisible" width="40%" @closed="editUserClose">
      <!-- 对话框主体 -->
      <el-form :model="editUserForm" ref="editUserRef" label-width="100px" :rules="editUserrules">
        <el-form-item label="用户名">
          <el-input disabled v-model="editUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserCheck">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoledialogVisible"
      width="50%"
      @closed="setRoleDialogClosed"
    >
      <p>当前用户 : {{setRole_userInfo.username}}</p>
      <p>当前角色 : {{setRole_userInfo.role_name}}</p>
      <p>
        分配新角色 :
        <el-select v-model="selectedId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoledialogComfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getUsersList()
    console.log(this.usersList)
  },
  data() {
    /* 添加用户 邮箱自定义验证规则 */
    var checkEmail = (rule, value, callback) => {
      const emailreg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (emailreg.test(value)) {
        return callback()
      }
      callback(new Error('请输入符合规则的邮箱'))
    }
    /* 添加用户 电话号码自定义验证规则 */
    var checkPhone = (rule, value, callback) => {
      const phonereg = /^1[3|4|5|7|8][0-9]{9}$/
      if (phonereg.test(value)) {
        return callback()
      }
      callback(new Error('请输入符合规则的电话号码'))
    }

    return {
      /* 查询用户列表参数 */
      queryInfo: {
        /* 搜索框中内容 */
        query: '',
        /* 当前页码 */
        pagenum: 1,
        /* 每页显示条数 */
        pagesize: 3
      },
      /* 用户列表数据 */
      usersList: [],
      total: 0,
      /* 控制添加用户对话框显示隐藏 */
      addUserVisible: false,
      /* 添加用户表单信息 */
      adduserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        id: ''
      },
      /* 添加用户表单验证规则 */
      adduserrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [{ validator: checkEmail, trigger: 'blur' }],
        mobile: [{ validator: checkPhone, trigger: 'blur' }]
      },
      /* 控制修改按钮对话框的显示隐藏 */
      editUserVisible: false,
      /* 修改按钮对话框的表单信息 */
      editUserForm: {
        username: '',
        mobile: '',
        email: ''
      },
      /* editUserForm表单验证规则 */
      editUserrules: {
        email: [{ validator: checkEmail, trigger: 'blur' }],
        mobile: [{ validator: checkPhone, trigger: 'blur' }]
      },
      /* 控制分配角色对话框显示隐藏 */
      setRoledialogVisible: false,
      /* 保存点击分配角色的当前用户信息 */
      setRole_userInfo: {},
      /* 角色列表 */
      rolesList: [],
      /* 分配角色中选中新角色 */
      selectedId: ''
    }
  },
  methods: {
    /* 获取用户列表数据 */
    async getUsersList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.usersList = res.data.users
      this.total = res.data.total
      console.log(this.usersList)
    },
    /* 监听 pagesize 改变事件 */
    handleSizeChange(newPagesize) {
      this.queryInfo.pagesize = newPagesize
    },
    /* 监听 pagenum 改变事件 */
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum
      this.getUsersList()
    },
    /* 监听 userstate 改变事件 */
    async userStateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
    },
    /* 监听 搜索框清空 事件 */
    clearInput() {
      this.getUsersList()
    },
    /* 监听 关闭添加用户对话框 事件 */
    adduserClosed() {
      console.log(this)
      this.$refs.adduserForm.resetFields()
    },
    /* 点击按钮，添加新用户 */
    addUserCheck() {
      this.$refs.adduserForm.validate(async valid => {
        if (!valid) {
          return
        }
        /* 验证通过，发送请求 */
        const { data: res } = await this.$http.post('/users', this.adduserForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        /* 刷新列表 */
        this.getUsersList()
        /* 关闭对话框 */
        this.addUserVisible = false
      })
    },
    /* 点击修改按钮获取editUserForm信息 */
    async showEditUser(id) {
      this.editUserVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editUserForm.mobile = res.data.mobile
      this.editUserForm.username = res.data.username
      this.editUserForm.email = res.data.email
      this.editUserForm.id = id
    },
    /* 监听 修改按钮对话框关闭 事件 */
    editUserClose() {
      this.$refs.editUserRef.resetFields()
    },
    /* 修改用户信息并提交 */
    editUserCheck() {
      this.$refs.editUserRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message('修改用户信息失败')
        }
        /* 重新获取用户数据 */
        this.getUsersList()
        this.$message.success('用户信息修改成功')
        /* 关闭对话框 */
        this.editUserVisible = false
      })
    },
    /* 删除用户 */
    async removeUser(id) {
      const confirmResult = await this.$confirm('是否删除此用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      /* 点击确定， 返回“confirm” */
      /* 点击取消， 返回“cancel” */
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)
        if (res.meta.status === 200) {
          this.getUsersList()
          this.$message.success('删除用户成功')
        }
      }
      if (confirmResult === 'cancel') {
        this.$message('已取消删除操作')
      }
    },
    /* 显示分配角色对话框 */
    async showSetRoleDialog(userInfo) {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.setRole_userInfo = ''
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.setRole_userInfo = userInfo
      this.setRoledialogVisible = true
    },
    /* 根据分配角色对话框，发送请求，设置角色 */
    async setRoledialogComfirm() {
      const { data: res } = await this.$http.put(
        'users/' + this.setRole_userInfo.id + '/role',
        { rid: this.selectedId }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getUsersList()
      this.setRoledialogVisible = false
    },
    /* 监听分配角色对话框关闭事件 */
    setRoleDialogClosed() {
      /* 复用一个变量要注意清空 */
      this.setRole_userInfo = ''
      this.selectedId = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  font-size: 12px;
  margin-bottom: 16px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-row {
  margin-bottom: 16px;
}
.el-pagination {
  margin-top: 16px;
}
</style>
